const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 获取用户的通知列表
router.get('/notifications', (req, res) => {
  const userId = req.user.id;
  
  db.query(`
    SELECT n.*, 
           u.username as sender_name,
           p.title as post_title
    FROM notifications n
    JOIN users u ON n.sender_id = u.id
    LEFT JOIN posts p ON n.post_id = p.id
    WHERE n.user_id = ?
    ORDER BY n.created_at DESC
  `, [userId], (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    res.json(results);
  });
});

// 标记通知为已读
router.put('/notifications/:id/read', (req, res) => {
  const { id } = req.params;
  const userId = req.user.id;

  db.query(
    'UPDATE notifications SET is_read = TRUE WHERE id = ? AND user_id = ?',
    [id, userId],
    (error) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json({ message: '通知已标记为已读' });
    }
  );
});

// 标记所有通知为已读
router.put('/notifications/read-all', (req, res) => {
  const userId = req.user.id;

  db.query(
    'UPDATE notifications SET is_read = TRUE WHERE user_id = ?',
    [userId],
    (error) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json({ message: '所有通知已标记为已读' });
    }
  );
});

module.exports = router; 